# -*- coding: UTF-8 -*-
"""
@author: tgy
@file: demo02.py
@time: 2022/02/15
"""
import requests
import random
from hashlib import md5
from openpyxl import load_workbook
from openpyxl import Workbook
import os
import time

# Set your own appid/appkey.
appid = '20220215001083944'
appkey = 'WieBrKza4aroGfsG_qMk'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path


def translate(query, from_lang="en", to_lang="zh"):
    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    if not query:
        print(f'{query}不能为空')
        return

    # Generate salt and sign
    def make_md5(s, encoding='utf-8'):
        return md5(s.encode(encoding)).hexdigest()

    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    # print(result)
    query_dst_res = ""

    for val in result['trans_result']:
        ...
        query_dst_res += (val['dst'] + "\n")

    return query_dst_res


def read_xlsx(path):
    ...
    wb = load_workbook(path)
    sheets = wb.sheetnames
    print(sheets)
    sheet_name = sheets[-1]
    sheet_content = wb[sheets[0]]
    rows = sheet_content.rows
    sava_xlsx = os.path.join("./", sheet_name + ".xlsx")
    save_wb = Workbook()
    save_wb_active = save_wb.active

    # count = 2
    flag = True

    for row in rows:
        ...
        line = [col.value for col in row]
        result = []
        if flag:
            ...
            flag = False
            result.extend(line)
        else:
            result.extend(line[0:2])
            result.append(translate(line[1]))
            time.sleep(1)
            result.append(line[2])
            result.append(translate(line[2]))
            time.sleep(1)
            result.extend(line[3:])
        save_wb_active.append(result)
        print(result)

    save_wb.save(sava_xlsx)


def test01():
    # _, dis = translate("鱼与熊掌不可兼得",from_lang="zh",to_lang="en")
    # print(dis)
    dis = translate(
        "HCl reacts with oxidizing acids such as HNO3 and H2SeO4, evolving toxic chlorine gas (Hisham, M.W.M., T.V. Bommaraju. 2004. Hydrogen Chloride. In Kirk-Othmer Encyclopedia of Chemical Technology. John Wiley & Sons, Inc. (Online))._x000D_\n_x000D_\nReactions of HCl with fuming H2SO4 or chlorosulfonic acid are violent (Lewis, R.J., Sr. 1992. Sax's Dangerous Properties of Industrial Materials, 8th Edition. New York: Van Nostrand Reinhold. pp. 1893.), and HCl is dehydrated by H2SO4, causing rapid evolution of large amounts of toxic HCl gas (MCA Case History No. 1785, Case Histories of Accidents in the Chemical Industry, Washington, Manufacturing Chemists' Association; Libman, D.D. 1948. Chemistry and Industry 728.)._x000D_\n_x000D_\nHF and methanesulfonic acid react violently to form explosive OF2 gas, which may be ignited by reaction heat (Lewis, R.J., Sr. 1992. Sax's Dangerous Properties of Industrial Materials, 8th Edition. New York: Van Nostrand Reinhold. pp. 1897.)._x000D_\n_x000D_\nHydrofluoric acid reacts violently with fuming H2SO4 (Bentzinger, von R. et al. 1987. Praxis Naturwiss. Chem. 36, 37.), and both HF and HCl enhance the oxidizing power of HNO3; solutions thereof can oxidize glycerol if glycerol is used as a solvent (Buck, R.H. 1966. Journal of Electrochemical Society 113:1352-1353; University Safety Association. 1992. Safety Digest 44:25.)._x000D_\n_x000D_\nSulfamic acid reacts with nitric acid to form nitrogen gas and NOx (predicted).")
    print(dis)


def test02():
    ...
    read_xlsx("./content.xlsx")


if __name__ == '__main__':
    pass
    test02()
